package com.simplefaith.delisty.util;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import com.simplefaith.delisty.user.UserModel;

public class LocationDetector {

	private LocationManager locationManager;
	private String strLocationPrivider = "";

	private UserModel user;

	public UserModel getUser() {
		return user;
	}

	private String mLocationMessage;

	public String getLocationMessage() {
		return mLocationMessage;
	}

	public void setLocationMessage(String locationMessage) {
		LocationDetector.this.mLocationMessage = locationMessage;
	}

	public LocationDetector(final Activity activity) {

		this.user = new UserModel();

		/* set Service of Manager */
		LocationDetector.this.locationManager = (LocationManager) activity
				.getSystemService(Context.LOCATION_SERVICE);

		/* first request for location */
		Location location = getLocationPrivider(locationManager);
		user.setLocation(location);

		/**
		 * set location update callback
		 * 
		 * @param provider
		 * @param min_time
		 * @param min_distance
		 * @param event
		 *            listener
		 * */
		LocationDetector.this.locationManager.requestLocationUpdates(
				strLocationPrivider, 2000, 10, mLocationListener);

	}

	public final LocationListener mLocationListener = new LocationListener() {
		@Override
		public void onLocationChanged(Location location) {

			/* update location while location changed */
			LocationDetector.this.user.setLocation(location);
			setLocationMessage(String.valueOf(location.getLatitude()) + ","
					+ String.valueOf(location.getLongitude()));
		}

		@Override
		public void onProviderDisabled(String provider) {

		}

		@Override
		public void onProviderEnabled(String provider) {

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {

		}
	};

	public Location getLocationPrivider(LocationManager lm) {
		Location retLocation = null;
		try {
			Criteria mCriteria01 = new Criteria();
			mCriteria01.setAccuracy(Criteria.ACCURACY_FINE);
			mCriteria01.setAltitudeRequired(false);
			mCriteria01.setBearingRequired(false);
			mCriteria01.setCostAllowed(true);
			mCriteria01.setPowerRequirement(Criteria.POWER_LOW);
			strLocationPrivider = lm.getBestProvider(mCriteria01, true);
			retLocation = lm.getLastKnownLocation(strLocationPrivider);
		} catch (Exception e) {
			setLocationMessage(e.toString());
			e.printStackTrace();
		}
		return retLocation;
	}
}
